package com.simp;

import com.simp.entity.CommonEntity;


/**
 * @author pan.shun
 * @since 2022/3/25 14:27
 */

def main() {
    try {
        StringBuilder stringBuilder = new StringBuilder()
        println("子类：")
        for (Class<?> c : getAllAssignedClass(CommonEntity.class)) {
            println(c.getName())
            stringBuilder.append(c.getName()).append("\r\n");
        }
        return stringBuilder.toString()
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace()
    }
}

/**
 * 获取同一路径下所有子类或接口实现类
 *
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
List<Class<?>> getAllAssignedClass(Class<?> cls) throws IOException,
        ClassNotFoundException {
    List<Class<?>> classes = new ArrayList<Class<?>>()
    for (Class<?> c : getClasses(cls)) {
        if (cls.isAssignableFrom(c) && !cls.equals(c)) {
            classes.add(c)
        }
    }
    return classes
}

/**
 * 取得当前类路径下的所有类
 *
 * @param cls
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 */
List<Class<?>> getClasses(Class<?> cls) throws IOException,
        ClassNotFoundException {
    String pk = cls.getPackage().getName()
    String path = pk.replace('.', '/')
    ClassLoader classloader = Thread.currentThread().getContextClassLoader()
    URL url = classloader.getResource(path)
    return getClasses(new File(url.getFile()), pk)
}

/**
 * 迭代查找类
 *
 * @param dir
 * @param pk
 * @return
 * @throws ClassNotFoundException
 */
List<Class<?>> getClasses(File dir, String pk) throws ClassNotFoundException {
    List<Class<?>> classes = new ArrayList<Class<?>>()
    if (!dir.exists()) {
        return classes
    }
    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            classes.addAll(getClasses(f, pk + "." + f.getName()))
        }
        String name = f.getName()
        if (name.endsWith(".class")) {
            classes.add(Class.forName(pk + "." + name.substring(0, name.length() - 6)))
        }
    }
    return classes
}